<?php

namespace App\Jobs;

use App\Episode;
use App\Jobs\Job;
use GuzzleHttp\Client;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Symfony\Component\DomCrawler\Crawler;

/**
 * Class FetchTtmjEpisodeDetailJob
 * @package App\Jobs   废弃
 */
class FetchTtmjEpisodeDetailJob extends Job implements ShouldQueue
{
    use InteractsWithQueue, SerializesModels;
    protected $ttmj_episode_url;
    protected $base_url = 'http://www.ttmeiju.com';
    protected $client;
    protected $episode;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(Episode $episode,$url)
    {
        $this->episode = $episode;
        $this->ttmj_episode_url = $this->base_url.$url;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        if ($this->attempts() > 2) {
            $this->delete();
            return;
        }

        $base_url = $this->ttmj_episode_url;
        $header_params = config('app.google_bot_headers');
        $header_params['referer'] = 'bbs.ttmeiju.com';
        $header_params['host'] = $base_url;
        //获取登陆cookie
        $this->client = new Client([
            'headers' => $header_params,
            'cookies' => true,
            'allow_redirects' => true,
            'base_uri' => $base_url
        ]);


        $response = $this->client->request('GET',$this->ttmj_episode_url);

        $html = $response->getBody()->getContents();
        $crawler = new Crawler($html);
        $episode = $this->episode;
        //处理链接地址
        $crawler->filter('ul.links > li:nth-child(1) > a')->each(function(Crawler $row,$i) use($episode){
            $value = $row->attr('href');
            if(str_contains($value,'baidu')) {
                $episode->url_baidupan = $value;
            }
            elseif(str_contains($value,'magnet')) {
                $episode->url_magnet = $value;
            }
            elseif(str_contains($value,'ed2k')) {
                $episode->url_ed2k = $value;

            }elseif(str_contains($value,'acfun')) {
                $episode->url_video = $value;
            }
            else {
                $episode->url_other = $value;
            }
            $episode->save();
        });



        echo $this->ttmj_episode_url;
    }
}
